package com.hao.tool.web.component.interceptor;

import com.hao.tool.common.security.JwtConstant;
import com.hao.tool.common.security.JwtSubject;
import com.hao.tool.common.security.JwtUtil;
import com.hao.tool.common.util.JsonKitUtil;
import com.hao.tool.web.common.constant.Commons;
import com.hao.tool.web.module.rbac.entity.ManagerInfo;
import com.hao.tool.web.module.rbac.service.ManagerService;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by haol on 2017/3/15.
 */
@Component
public class WebInterceptor extends HandlerInterceptorAdapter {


    private ManagerService managerService;

    public WebInterceptor(ManagerService managerService) {
        this.managerService = managerService;
    }

    Logger logger = LoggerFactory.getLogger(WebInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        try {
            String token = JwtUtil.getTokenValueByCookie(request, JwtConstant.COOKIE_NAME);
            Claims claims = JwtUtil.analyzeAndGetJWT(token);
            JwtSubject jwtSubject = JsonKitUtil.getObject(claims.getSubject(), JwtSubject.class);
            request.setAttribute(Commons.SUB_KEY, jwtSubject.getAccount());
            ManagerInfo managerInfo = managerService.findByAccount(jwtSubject.getAccount());
            if (managerInfo == null) {
                throw new Exception("用户不存在");
            }
            request.setAttribute(Commons.MANAGER, managerInfo);

        } catch (Exception e) {

        }
        return true;
    }
}